<!DOCTYPE html >
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>查看二维码</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link href="base.css" rel="stylesheet" type="text/css" media="screen"/>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script src="weapp-qrcode.js" type="text/javascript"></script>
</head>
<body>

<div class="content" id="content">
    <div id="check-code">
        <div class="bg">
            <div>
                <img src="huarunlogo.png" >
            </div>
        </div>
        <div class="check-code-title">请输入<span class="project"></span>大厦访客验证码</div>
        <div class="content-padded" style="margin: 0;margin-top: 10px;">
            <div class="row" id="forms" style="margin-left:0">
                <div class="col-20">验证码</div>
                <div class="col-50" style="height: 100%;"><input style="border:none;" type="" name="recode" id="recode" value="" placeholder="请输入验证码" /></div>
                <div class="col-20" style="display: flex;justify-content: center;">
                    <div id="submitBtn" type="button" >确认</div>
                </div>
            </div>
        </div>


    </div>

    <div id="show-recode">
        <div class="show-recode-title"><span class="project"></span>大厦访客二维码</div>
        <div class="show-recode-img">
            <div class="img">
                <img id="img" src=""  class="code-img">
            </div>
            <div id="disabled">
                <div class="disabled-content">
                    访问时间已过，凭证已失效
                </div>
            </div>
        </div>
        <div class="text">
            <div>有效访问时间为：</div>
            <div><span class="start-time"></span>  至 <span class="end-time"></span> </div>
            <div>注：</div>
            <div>1.实行一人一码</div>
            <div>2.如无法正常使用时请到前台登记访问</div>
        </div>
    </div>
</div>

<div class="msg" >
    <div id="msg">拜访时间已过，二维码已失效，请重新预约</div>
</div>
</body>
</html>

<script type="text/javascript">
    var projects = [{
        value:'a3697350-929a-f808-f97e-c6b9f499059b',
        label:'春笋',
    },{
        value:'4f7a8c26-27a7-4e2b-5175-d6f1080ff897',
        label:'B座',
    },{
        value:'b2b27417-c4d2-efe2-bfad-e1634da2b2a4',
        label:'C座',
    },{
        value:'46926a20-4f4d-3c70-6c97-f5996b56c73a',
        label:'D座',
    },{
        value:'9f7a5912-e560-47f9-9045-b870eeef4876',
        label:'E座',
    }]


    var state = [{
        value:-1,
        label:'验证',
        msg:"验证成功"
    },{
        value:-2,
        label:'未验证',
        msg:"验证码有误，请重新输入"
    },{
        value:-3,
        label:'未开始',
        msg:"未到拜访时间，暂时无法查看二维码"
    },{
        value:-4,
        label:'已过期',
        msg:"拜访时间已过，二维码已失效，请重新预约"
    },{
        value:-5,
        label:'已取消',
        msg:"预约已取消，无法查看凭证"
    }]

    // 工具函数
    var helper = {
        // 获取消息文本
        getStateMsg:function(value){
            var msg = '';
            state.forEach(function(v,k){
                if(v.value == value){
                    msg = v.msg
                }
            })
            return msg
        },

        // 获取项目名称
        getProjectLabel:function(value){
            var msg = '';
            projects.forEach(function(v,k){
                if(v.value == value){
                    msg = v.label
                }
            })
            return msg
        },
        // 截取url参数
        getQueryString:function(name){
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);//search,查询？后面的参数，并匹配正则
            if(r!=null)return  unescape(r[2]); return null;
        },
        // 时间格式化
        formatDate:function(date, fmt) {
            date = date == undefined ? new Date() : date;
            date = typeof date == 'number' ? new Date(date) : date;
            fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
            var obj = {
                'y': date.getFullYear(),
                'M': date.getMonth() + 1,
                'd': date.getDate(),
                'q': Math.floor((date.getMonth() + 3) / 3), // 季度
                'w': date.getDay(),
                'H': date.getHours(),
                'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12,
                'm': date.getMinutes(),
                's': date.getSeconds(),
                'S': date.getMilliseconds()
            };
            var week = ['天', '一', '二', '三', '四', '五', '六'];
            for (var i in obj) {
                fmt = fmt.replace(new RegExp(i + '+', 'g'), function (m) {
                    var val = obj[i] + '';
                    if (i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
                    for (var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
                    return m.length == 1 ? val : val.substring(val.length - m.length);
                });
            }
            return fmt;
        }
    }

    function getServerPath() {
        return `${window.location.origin}`;
    }

    // 截取url
    // var server = 'http://192.168.60.41:6616/huarun/wx/';
    // var server = 'https://wgxcx.crland.com.cn/huarun/wx/'; // UAT环境
    var server = getServerPath()+'/huarun/wx/';  // PROD 环境
    var code = '';//验证码
    var applyId = '';
    var projectId = '';
    var interval;//定时查询是否过期
    var startTimeFormat;//保存的时间
    var endTimeFormat;//保存的时间
    var endTime;//截止时间
    var isCheckCode = false;

    function saveUrlInfo(){
        applyId = parseInt(helper.getQueryString('applyId'));
        projectId = helper.getQueryString('projectId');
    }

    saveUrlInfo()

    $(function() {
        // 交互元素
        var $dom = {
            inputRecode:$('#recode'),//填写的验证码
            submitBtn: $('#submitBtn'),//提交按钮
            project:$('.project'),//项目名字
            checkCode:$('#check-code'),//检查验证码界面
            showRecode:$('#show-recode'),//显示验证码界面
            startTime:$('.start-time'),//开始时间
            endTime:$('.end-time'),//截止时间
            msgBox:$('.msg'),//消息外部容器
            msg:$('#msg'),//消息文本
            disabled:$('#disabled'),//禁用容器
            disabledText:$('.disabled-content'),//禁用容器文本
            codeImgBox:$('.img'),//二维码容器
            codeImg:$('#img'),//二维码图片
        }

        // jquery 工具类
        var $helper = {
            showStateMsg:function(state){
                var msg = helper.getStateMsg(state);
                $helper.showMsg(msg)
            },
            showMsg:function(msg){
                var showMsg = '网络异常,请稍后再试'
                if(msg){
                    showMsg = msg;
                }
                $('.msg').show()
                $('#msg').text(showMsg)
                setTimeout(function(){
                    $('#msg').text('')
                    $('.msg').hide()
                },3000)
            },
            send:function(url,params,callback){
                var data =  JSON.stringify(params);
                $.ajax({
                    type: 'POST',
                    url: server + url ,
                    data: data,
                    cache:false,
                    dataType: 'json',
                    timeout:10000,
                    contentType: 'application/json;charset=utf-8',
                    success: function (res) {
                        callback(res)
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        // alert(XMLHttpRequest.status);
                        // alert(XMLHttpRequest.readyState);
                        // alert(textStatus);
                        alert('网络异常，请刷新页面或稍后再试')
                    }
                })
            },
            // 显示验证界面
            showCheckCodeView:function(){
                $dom.checkCode.show();
                $dom.showRecode.hide();
            },
            // 显示二维码界面
            showRecodeContentView:function(){
                $dom.checkCode.hide();
                $dom.showRecode.show();
            }
        }

        function runInterval(){
            interval = setInterval(function(){
                getMeCode();
            }, 10000)
        }

        var init = {
            // 设置项目名字
            setProjectLabe:function(){
                var label = helper.getProjectLabel(projectId);
                $dom.project.text(label)
            },
            // 是否验证过
            isCheckedCode:function(){
                $dom.codeImgBox.hide();
                if(applyId !== '' && localStorage.isChecked === applyId){
                    $helper.showRecodeContentView()
                    code = parseInt(localStorage.code);
                    // 存储本地时间
                    $dom.startTime.text(localStorage.startTimeFormat);
                    $dom.endTime.text(localStorage.endTimeFormat);

                    getMeCode();

                    setTimeout(function(){
                        getMeCode();
                    },2000)

                    runInterval();
                }else{
                    localStorage.startTimeFormat = '';
                    localStorage.endTimeFormat = ''
                    clearInterval(interval)
                    $helper.showCheckCodeView()
                }
            }
        }

        init.setProjectLabe();
        init.isCheckedCode();

        //消息
        function showMsg(msg){
            $('.msg').show()
            $('#msg').text(msg)

            setTimeout(function(){
                $('#msg').text('')
                $('.msg').hide()
            },3000)
        }


        // 隐藏二维码界面
        function hideRecodeImg(text){
            $dom.disabledText.text(text)
            $dom.disabled.show()
            $dom.codeImgBox.hide();
        }
        // 显示二维码界面
        function showRecodeImg(data){
            startTimeFormat = helper.formatDate(data.startTime * 1000,'yyyy-MM-dd HH:mm');
            endTimeFormat = helper.formatDate(data.endTime * 1000,'yyyy-MM-dd HH:mm');

            localStorage.startTimeFormat = startTimeFormat;
            localStorage.endTimeFormat = endTimeFormat

            $dom.startTime.text(startTimeFormat);
            $dom.endTime.text(endTimeFormat);

            $dom.codeImgBox.show();
            $dom.disabled.hide()
            // 春笋的是返回code前端生成二维码，其他是直接返回的地址
            var twoCode = data.twoCode;
            if("a3697350-929a-f808-f97e-c6b9f499059b" === projectId){
                var options = {typeNumber:4,errorCorrectLevel:'M',size:200};
                twoCode = drawImg(twoCode,options);
            }
            $dom.codeImg.attr('src',twoCode);
        }

        // 请求获取二维码
        function getMeCode(){
            $helper.send('newVisitorApply/getMeCode',{ code: code,applyId:applyId,projectId:projectId },function(res){
                console.log(res)
                if(res.code == 200){
                    var data = res.data;
                    var msg = res.message;
                    if(msg == -1 || msg == "-1"){
                        showRecodeImg(data);
                    }else{
                        if(msg == -2 || msg == "-2"){
                            localStorage.isChecked === '';
                            hideRecodeImg('没有验证，无权查看凭证');
                            clearInterval(interval)
                            $helper.showCheckCodeView()
                        }
                        if(msg == -3 || msg == "-3"){
                            hideRecodeImg('未到拜访时间，暂时无法查看二维码');
                        }
                        if(msg == -4 || msg == "-4"){
                            hideRecodeImg('访问时间已过，凭证已失效');
                        }
                        if(msg == -5 || msg == "-5"){
                            hideRecodeImg('邀约已被取消');
                        }
                    }
                }else{
                    $helper.showMsg();
                }
            })
        }

        // 验证是否成功
        function checkSuccess(){
            localStorage.isChecked = applyId;
            isCheckCode = true;
            $helper.showRecodeContentView();
            getMeCode();
            setTimeout(function(){
                getMeCode();
            },2000)
            runInterval();
        }
        // 794007
        $dom.submitBtn.click(function(){
            var inputVal = $dom.inputRecode.val();
            var val = parseInt(inputVal) || '';
            var params = {
                code: val,
                applyId:applyId
            }
            setTimeout(function(){
                try{
                    $helper.send('newVisitorApply/getCheckCode',params,function(res){
                        if(res.code === 200){
                            $helper.showStateMsg(res.data)
                            if(res.data == -1 || res.data == "-1"){
                                code = val;
                                localStorage.code = code;
                                checkSuccess();
                            }
                        }else{
                            $helper.showMsg(res.message)
                        }
                    })
                }catch(e){

                }
            },100)
        })
    })
</script>
